﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;

using System.Windows;
using System.Windows.Controls;
using AutoLoL.Dialogs;
using AutoLoL.Logic;
using AutoLoL.Logic.Game;
using AutoLoL.Logic.Utils;
using AutoLoL.Shared;

namespace AutoLoL.Tabs
{
    public delegate void SettingsSavedHandler();
    public delegate void BuildsImportedHandler();

    public partial class SettingsTab : System.Windows.Controls.UserControl
    {
        public event SettingsSavedHandler OnSettingsSaved;
        public event BuildsImportedHandler OnBuildsImported;

        public bool ImportButtonEnabled
        {
            get { return ImportButton.IsEnabled; }
            set { ImportButton.IsEnabled = value; }
        }

        public SettingsTab()
        {
            InitializeComponent();

            foreach (int key in Constants.AUTOCHAT_MODIFIER_KEYS.Keys)
            {
                ModifierKeyComboBox.Items.Add(new ComboBoxItem()
                {
                    Tag = key,
                    Content = new TextBlock() { Text = Constants.AUTOCHAT_MODIFIER_KEYS[key] }
                });
            }

            foreach (int[] key in Constants.AUTOCHAT_KEYS.Keys)
            {
                KeysComboBox.Items.Add(new ComboBoxItem()
                {
                    Tag = String.Join(",", key),
                    Content = new TextBlock() { Text = Constants.AUTOCHAT_KEYS[key] }
                });
            }

            UpdateFromUserSettings();
            SetEnabled(false);
        }

        private void EditButton_Click(object sender, RoutedEventArgs e)
        {
            SetEnabled(true);
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            UserSettings.Instance.LolDirectory = LolDirectoryTextBox.Text;
            UserSettings.Instance.IsAutorunEnabled = AutorunCheckBox.IsChecked.Value;

            UserSettings.Instance.IsManualReturnEnabled = ManualReturnCheckBox.IsChecked.Value;

            UserSettings.Instance.IsAutoChatEnabled = AutoChatCheckBox.IsChecked.Value;
            UserSettings.Instance.AutoChatModifierKey = int.Parse(((ComboBoxItem)ModifierKeyComboBox.SelectedItem).Tag.ToString());
            UserSettings.Instance.AutoChatKeys = ((ComboBoxItem)KeysComboBox.SelectedItem).Tag.ToString().Split(',').Select(c => int.Parse(c)).ToArray();

            UserSettings.Instance.LolUsername = LolUsernameTextBox.Text;
            if (!string.IsNullOrEmpty(LolPasswordTextBox.Password))
            {
                UserSettings.Instance.LolPasswordEncrypted = Encryption.Protect(LolPasswordTextBox.Password);
            }
            UserSettings.Instance.IsAutoLoginEnabled = AutoLoginCheckBox.IsChecked.Value;

            UserSettings.Instance.IsMinimizeToTrayEnabled = MinimizeToTrayCheckBox.IsChecked.Value;

            UserSettings.Instance.Save();

            if (OnSettingsSaved != null)
            {
                OnSettingsSaved();
            }

            SetEnabled(false);
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            UpdateFromUserSettings();
            SetEnabled(false);
        }

        private void SetEnabled(bool isEnabled)
        {
            if (isEnabled)
            {
                EditButton.Visibility = Visibility.Collapsed;
                SaveButton.Visibility = Visibility.Visible;
                CancelButton.Visibility = Visibility.Visible;
            }
            else
            {
                EditButton.Visibility = Visibility.Visible;
                SaveButton.Visibility = Visibility.Collapsed;
                CancelButton.Visibility = Visibility.Collapsed;
            }

            AutorunCheckBox.IsEnabled = isEnabled;

            ManualReturnCheckBox.IsEnabled = isEnabled;

            AutoChatCheckBox.IsEnabled = isEnabled;
            ModifierKeyComboBox.IsEnabled = isEnabled;
            KeysComboBox.IsEnabled = isEnabled;

            LolUsernameTextBox.IsEnabled = isEnabled;
            LolPasswordTextBox.IsEnabled = isEnabled;
            AutoLoginCheckBox.IsEnabled = isEnabled;

            // TODO - Remove comment
            //MinimizeToTrayCheckBox.IsEnabled = isEnabled;
        }

        public void UpdateFromUserSettings()
        {
            LolDirectoryTextBox.Text = UserSettings.Instance.LolDirectory;
            AutorunCheckBox.IsChecked = UserSettings.Instance.IsAutorunEnabled;

            ManualReturnCheckBox.IsChecked = UserSettings.Instance.IsManualReturnEnabled;

            AutoChatCheckBox.IsChecked = UserSettings.Instance.IsAutoChatEnabled;
            ModifierKeyComboBox.SelectedItem = GetItemFromTag(ModifierKeyComboBox, UserSettings.Instance.AutoChatModifierKey.ToString());
            KeysComboBox.SelectedItem = GetItemFromTag(KeysComboBox, String.Join(",", UserSettings.Instance.AutoChatKeys.Select(c => c.ToString()).ToArray()));

            LolUsernameTextBox.Text = UserSettings.Instance.LolUsername;
            if (!string.IsNullOrEmpty(UserSettings.Instance.LolPasswordEncrypted))
            {
                LolPasswordTextBox.Password = Logic.Utils.Encryption.Unprotect(UserSettings.Instance.LolPasswordEncrypted);
            }
            AutoLoginCheckBox.IsChecked = UserSettings.Instance.IsAutoLoginEnabled;

            MinimizeToTrayCheckBox.IsChecked = UserSettings.Instance.IsMinimizeToTrayEnabled;
        }

        private ComboBoxItem GetItemFromTag(ComboBox target, string tag)
        {
            return target.Items.Cast<ComboBoxItem>().Where(c => c.Tag.ToString().Equals(tag)).SingleOrDefault();
        }

        public static bool IsValidLolDirectory(string directory)
        {
            if (!string.IsNullOrEmpty(directory)
                && Directory.Exists(directory)
                // && File.Exists(System.IO.Path.Combine(directory, "lol.launcher.exe")) // Removed to add compatibility for Yaric
                && Directory.Exists(System.IO.Path.Combine(directory, "RADS")))
            {
                return true;
            }

            return false;
        }

        private void ImportButton_Click(object sender, RoutedEventArgs e)
        {
            ImportLolmDialog importLolmDialog = new ImportLolmDialog();
            importLolmDialog.ShowDialog();

            if (importLolmDialog.ViewModel.LolmFiles.Where(f => f.Imported).Count() > 0)
            {
                if (OnBuildsImported != null)
                {
                    OnBuildsImported();
                }
            }
        }
    }
}
